<template>
    <div class="api-management">
        <h1>API管理页</h1>
        
        <div class="search-bar">
            <el-input
                v-model="searchName"
                placeholder="API名称搜索"
                style="width: 200px; margin-right: 10px;"
                clearable
                @clear="resetSearch"
            ></el-input>
            <el-button type="primary" @click="searchApis">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
        </div>
        
        <el-table 
            :data="apis" 
            border 
            style="width: 100%; margin-top: 20px"
            @sort-change="handleSortChange"
        >
            <el-table-column prop="id" label="ID" width="80" sortable="custom"></el-table-column>
            <el-table-column prop="name" label="API名称" width="150" sortable="custom"></el-table-column>
            <el-table-column prop="method" label="请求方法" width="100" sortable="custom">
                <template v-slot="scope">
                    <el-tag
                        :type="getMethodTagType(scope.row.method)"
                    >{{ scope.row.method }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="path" label="API路径" sortable="custom"></el-table-column>
            <el-table-column prop="description" label="API描述"></el-table-column>
            <el-table-column label="创建/更新时间" width="200">
                <template v-slot="scope">
                    <div>创建: {{ formatDateTime(scope.row.createdAt) }}</div>
                    <div>更新: {{ formatDateTime(scope.row.updatedAt) }}</div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template v-slot="scope">
                    <el-button type="primary" size="small" @click="showUpdateForm(scope.row.id)">编辑</el-button>
                    <el-button type="danger" size="small" @click="confirmDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <div class="pagination-block" style="margin-top: 20px; text-align: right;">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            >
            </el-pagination>
        </div>
        
        <el-button type="success" style="margin-top: 20px" @click="showAddForm">新增</el-button>

        <el-dialog
            :title="currentApi.id ? '编辑API' : '新增API'"
            :visible.sync="showSaveForm"
            width="40%"
            @close="resetForm"
        >
            <el-form
                :model="currentApi"
                ref="apiForm"
                label-width="100px"
                style="padding: 0 20px"
            >
                <el-form-item label="API ID">
                    <el-input v-model="currentApi.id" readonly></el-input>
                </el-form-item>
                <el-form-item label="API名称" prop="name">
                    <el-input v-model="currentApi.name"></el-input>
                </el-form-item>
                <el-form-item label="请求方法" prop="method">
                    <el-select v-model="currentApi.method" placeholder="请选择请求方法">
                        <el-option label="GET" value="GET"></el-option>
                        <el-option label="POST" value="POST"></el-option>
                        <el-option label="PUT" value="PUT"></el-option>
                        <el-option label="DELETE" value="DELETE"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="API路径" prop="path">
                    <el-input v-model="currentApi.path"></el-input>
                </el-form-item>
                <el-form-item label="API描述" prop="description">
                    <el-input type="textarea" v-model="currentApi.description" rows="4"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showSaveForm = false">取消</el-button>
                <el-button type="primary" @click="saveApi">保存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'ApiManagement',
    data() {
        return {
            apis: [],
            total: 0,
            pageNum: 1,
            pageSize: 10,
            searchName: '',
            orderBy: null,
            showSaveForm: false,
            currentApi: {
                id: '',
                name: '',
                method: 'GET',
                path: '',
                description: '',
            }
        };
    },
    created() {
        this.loadApis();
    },
    methods: {
        loadApis() {
            if (this.searchName) {
                this.searchApis();
            } else {
                this.$axios
                    .get('/api/page', {
                        params: {
                            pageNum: this.pageNum,
                            pageSize: this.pageSize,
                            orderBy: this.orderBy
                        }
                    })
                    .then(response => {
                        if (response.data.success) {
                            this.apis = response.data.data.list;
                            this.total = response.data.data.total;
                        }
                    })
                    .catch(error => {
                        console.error('获取API列表失败', error);
                        this.$message.error('获取API列表失败');
                    });
            }
        },
        searchApis() {
            if (!this.searchName) {
                this.loadApis();
                return;
            }
            
            this.$axios
                .get('/api/search', {
                    params: {
                        name: this.searchName,
                        pageNum: this.pageNum,
                        pageSize: this.pageSize
                    }
                })
                .then(response => {
                    if (response.data.success) {
                        this.apis = response.data.data.list;
                        this.total = response.data.data.total;
                    }
                })
                .catch(error => {
                    console.error('搜索API失败', error);
                    this.$message.error('搜索API失败');
                });
        },
        resetSearch() {
            this.searchName = '';
            this.pageNum = 1;
            this.loadApis();
        },
        handleSizeChange(size) {
            this.pageSize = size;
            this.loadApis();
        },
        handleCurrentChange(page) {
            this.pageNum = page;
            this.loadApis();
        },
        handleSortChange({prop, order}) {
            if (order === 'ascending') {
                this.orderBy = `${prop} asc`;
            } else if (order === 'descending') {
                this.orderBy = `${prop} desc`;
            } else {
                this.orderBy = null;
            }
            this.loadApis();
        },
        showUpdateForm(id) {
            this.$axios
                .get(`/api/getById/${id}`)
                .then(response => {
                    if (response.data.success) {
                        this.currentApi = { ...response.data.data };
                        this.showSaveForm = true;
                    }
                })
                .catch(error => {
                    console.error('获取API信息失败', error);
                    this.$message.error('获取API信息失败');
                });
        },
        showAddForm() {
            this.currentApi = {
                id: '',
                name: '',
                method: 'GET',
                path: '',
                description: '',
            };
            this.showSaveForm = true;
        },
        saveApi() {
            this.$axios
                .post('/api/save', this.currentApi)
                .then(response => {
                    if (response.data.success) {
                        this.$message.success('保存成功');
                        this.showSaveForm = false;
                        this.loadApis();
                    }
                })
                .catch(error => {
                    console.error('保存API失败', error);
                    this.$message.error('保存失败');
                });
        },
        confirmDelete(id) {
            this.$confirm('确认删除此API?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteApi(id);
            }).catch(() => {
                // 取消删除
            });
        },
        deleteApi(id) {
            this.$axios
                .delete(`/api/delete/${id}`)
                .then(response => {
                    if (response.data.success) {
                        this.$message.success('删除成功');
                        this.loadApis();
                    }
                })
                .catch(error => {
                    console.error('删除API失败', error);
                    this.$message.error('删除失败');
                });
        },
        resetForm() {
            this.currentApi = {
                id: '',
                name: '',
                method: 'GET',
                path: '',
                description: '',
            };
        },
        formatDateTime(dateTime) {
            if (!dateTime) return '';
            return dateTime;
        },
        getMethodTagType(method) {
            const types = {
                'GET': 'success',
                'POST': 'primary',
                'PUT': 'warning',
                'DELETE': 'danger'
            };
            return types[method] || 'info';
        }
    }
};
</script>

<style scoped>
.api-management {
    padding: 20px;
}
.search-bar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}
</style> 